package org.streets.commons.expression;


/**
 * 表达式
 * 
 * @author dzb
 */
public class Express {
	// 左操作数: value || Express
	private Object exp;
	// 操作符
	private Operation op;
	// 右操作数 表达式
	private Express opExp;

	public Express(Object exp) {
		this.exp = exp;
	}

	public Operation setOp(Operation op) {
		this.op = op;
		return op;
	}

	public Express setOpExp(Express opExp) {
		this.opExp = opExp;
		return opExp;
	}

	/**
	 * @return value: boolean、number
	 */
	public Object eval(ExpressValueProvider ee) {
		if (op != null) {
			if (opExp.op == null) {
				// 聚合节点(即刮号表达式根节点)，先计算
				return op.eval(new EvalCommand(exp, ee), new EvalCommand(opExp,
						ee));
			} else {
				// 非聚合节点，LTR(左根右)遍历
				EvalCommand left = new EvalCommand(null, ee) {
					public Object evalValue() {
						return op.eval(new EvalCommand(exp, ee),
								new EvalCommand(opExp.exp, ee));
					}
				};
				return opExp.op.eval(left, new EvalCommand(opExp.opExp, ee));
			}
		}
		return new EvalCommand(exp, ee).evalValue();
	}

	public String toString() {
		return String.valueOf(exp);
	}
}
